package utilities;

import java.io.*;
import java.lang.reflect.Method;
import java.util.*;

import org.mozilla.javascript.Delegator;

public class Processor extends Thread {

	protected String name;
	protected BufferedWriter log;
	private int debug = 0;
	protected List workQueue;
	private Object configData;
	protected boolean active;
	protected int sleeps = 1000;
	protected boolean running = true;
	protected ProcessorCommander pc;
	
	public Processor()
	{}
	
	public void newProcessor(String name, BufferedWriter log, List workQueue,
			ProcessorCommander pc,
		 int sleeps, int debug)
	{
		this.name=name;
		this.log = log;
		this.workQueue = workQueue;
		this.sleeps = sleeps;
		this.processConfig();
		this.debug=debug;
		this.pc=pc;
	}
	
	public Processor(String name, BufferedWriter log, List workQueue, 
			Object configData
			, int sleeps)
	{
		this.name=name;
		this.log = log;
		this.workQueue = workQueue;
		this.configData = configData;
		this.sleeps = sleeps;
		this.processConfig();
	}
	public void exit()
	{
		running = false;
	}
	public void run()
	{
		try
		{
        String key;
		active = true;
		int actSize = 0;
		while(running)
			{
				if(active)
				{
					//get all actions available, process each one
					actSize =workQueue.size();
					for(int i=0; i< actSize;i++)
					{
						//process each action
						 key = workQueue.get(i).toString();
						 
						 //log.write("Processing key: " + key + "\n");
						 
						 processKey(key);						
					}
					for(int i=0; i< actSize;i++)
					{
						//remove action
						workQueue.remove(0);
					}					
				}	
			this.sleep(sleeps);
			
			try
			{
				//if(debug==5)	log.write("    cycle \n");
			}catch(Exception ee) {}			
			
			}
		}
		catch(Exception e)
		{
			try
			{
			log.write("Thread died: " + name + "\n" + e.getMessage());
			}catch(Exception ee) {}
		}
	}

	private void close()
	{
		//this.destroy();
	}
	
	private void processKey(String key)
	{						
		KeyActions pf = pc.getFilterByName(key);
		if(pf!=null)
		{
			for(Iterator it = pf.getActions().iterator();it.hasNext();)
			{
				servers.Dragon.delgator((ProcFilter)it.next());				
			}
		}						
	}
	private void processConfig()
	{}
	
	
	public void deActivate()
	{
		active = false;
	}
	public void activate()
	{
		active = true;
	}
	
	public int getSleeps() {return sleeps;}
	public void setSleeps(int sleeps)
	{
		this.sleeps = sleeps;
	}
	public boolean getActive() {return active;}
	
	public void setConfigData(Object configData)
	{
		this.configData = configData;
	}
	public Object getConfigData() {return configData;}
	
}
